// 新增授课模块
document.querySelectorAll('.course-selector').forEach(selector => {
    const trigger = selector.querySelector('.selected-course');
    const list = selector.querySelector('.course-list');

    // 点击触发器
    trigger.addEventListener('click', (e) => {
        e.stopPropagation();

        list.style.display =list.style.display === 'block' ? 'none' : 'block';
        // 检查类名状态
        // console.log(document.querySelector('.course-list').classList)

// 强制显示测试

    });


});
// 更新课程选择框中的内容(课程ID 课程名称 学分)
document.querySelectorAll('.course-item').forEach(item => {
    item.addEventListener('click', (e) => {
        // 阻止事件冒泡
        e.stopPropagation();

        // 获取课程信息元素
        const courseCode = item.querySelector('.course-code').textContent;
        const courseName = item.querySelector('.course-name').textContent;
        const courseCredit = item.querySelector('.course-credit').textContent;

        // 更新选中显示区域
        const selectedArea = item.closest('.course-selector').querySelector('.selected-course');
        selectedArea.innerHTML = `
            <i class="fas fa-book-open"></i>
            <span class="course-text">${courseCode} | ${courseName} | ${courseCredit}</span>
            <i class="fas fa-chevron-down"></i>
        `;

        // 隐藏下拉列表
        const list = item.closest('.course-list');
        list.style.display = 'none';

        // 更新隐藏字段（如果需要）
        const courseId = item.dataset.courseId;
        document.querySelector('[name="courseId"]').value = courseId;
        const selector = item.closest('.course-selector');
        selector.classList.remove('invalid');
        selector.querySelector('.error-msg').style.display = 'none';
        // console.log(courseId);
    });
});
//获得className
document.querySelector('select[name="classId"]').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    const className = selectedOption.dataset.class;  // 使用dataset获取
    const classId = this.value;

    // 如果需要可以设置到隐藏字段
    document.querySelector('[name="className"]').value = className;
    // console.log("选中的班级ID:", classId, "名称:", className);
});

document.getElementById('createLectureBtn').addEventListener('click', function() {
    // e.preventDefault();

    console.log('点击了创建授课计划按钮')
    const form = document.querySelector('.advanced-lecture-form');
    // console.log(form)

    // 表单验证逻辑
    if (!validateForm(form)) {
        showToast('请填写所有必填项', 'warning');
        // console.log('请填写所有必填项')
        return;
    }

    // 显示确认弹窗
    showConfirmationModal(form);
});
// 显示确认弹窗（复用原有弹窗逻辑）
function showConfirmationModal(form) {
    // console.log('显示确认弹窗')
    const modal = document.createElement('div');
    modal.className = 'confirmation-modal';
    modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h4><i class="fas fa-check-circle"></i> 确认提交</h4>
                </div>
                <div class="modal-body">
                    <p>是否确认创建本次授课计划？</p>
                </div>
                <div class="modal-footer">
                    <button class="btn-modal btn-cancel">取消</button>
                    <button class="btn-modal btn-confirm">确定</button>
                </div>
            </div>
        `;

    const confirmBtn = modal.querySelector('.btn-confirm');
    const cancelBtn = modal.querySelector('.btn-cancel');

    // 新增处理逻辑
    const handleConfirm = async () => {
        confirmBtn.disabled = true; // 防止重复点击
        confirmBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 创建成功';

        try {
            await submitFormData(form); // 修改为异步调用
            modal.remove();
            showSuccessToast();
        } catch (error) {
            console.error('提交失败:', error);
        } finally {
            confirmBtn.disabled = false;
            confirmBtn.innerHTML = '确定';
        }
    };

    confirmBtn.addEventListener('click', handleConfirm);
    cancelBtn.addEventListener('click', () => modal.remove());

    document.body.appendChild(modal);
}


// 新增成功提示函数
function showSuccessToast() {
    const toast = document.createElement('div');
    toast.className = 'success-toast';
    toast.innerHTML = `        <i class="fas fa-check-circle"></i>
        <span>授课计划创建成功</span>
    `;

    document.body.appendChild(toast);

    // 3秒后自动消失
    setTimeout(() => {
        toast.style.animation = 'slideOut 0.3s ease-out';
        setTimeout(() => toast.remove(), 300);
    }, 1000);
}

// 表单验证函数
function validateForm(form) {
    let isValid = true;
    form.querySelectorAll('[required]').forEach(input => {
        if (!input.value.trim()) {
            input.classList.add('invalid');
            isValid = false;
        } else {
            input.classList.remove('invalid');
        }
    });
    document.querySelectorAll('[data-required="true"]').forEach(dropdown => {
        const hiddenInput = document.querySelector('#selectedCourseId');
        if (!hiddenInput.value.trim()) {
            dropdown.classList.add('invalid');
            dropdown.querySelector('.error-msg').style.display = 'block';
            isValid = false;
        } else {
            dropdown.classList.remove('invalid');
            dropdown.querySelector('.error-msg').style.display = 'none';
        }
    });
    return isValid;
}


// 实际提交逻辑
function submitFormData(form) {
    // alert("提交")
    const formData = new FormData(form);
    for (let [key, value] of formData.entries()) {
        console.log(key + ':', value);
    }
    const jsonData = {
        courseId: document.querySelector('[name="courseId"]').value,
        className: document.querySelector('[name="className"]').value,
        lectureTime: document.querySelector('[name="lectureTime"]').value,
        classroom: document.querySelector('[name="classroom"]').value,
        summary: document.querySelector('[name="summary"]').value
    };
    console.log('提交数据:', JSON.stringify(jsonData, null, 2));
    // console.log("formData"+formData)
   return new Promise((resolve,reject)=>{
       $.ajax({
           url: 'http://localhost:9220/AttendanceSystem/AddLectureController',
           type: 'POST',
           dataType: 'json',
           contentType: 'application/json',
           data: JSON.stringify(jsonData),
           // data: formData,

           success: function (data) {
               resolve(data);
               console.log("解析后的数据:", data);

           },
           error: function (xhr, status, error) {
               console.group("AJAX错误详情");
               console.log("HTTP状态码:", xhr.status);
               console.log("原始响应:", xhr.responseText);
               console.log("错误状态:", status);
               console.groupEnd();

               try {
                   const resp = JSON.parse(xhr.responseText);
                   console.log("解析后的错误信息:", resp);
               } catch(e) {
                   console.error("响应不是合法JSON");
               }
               // 处理错误响应
               // showToast('创建失败: ' + error, 'error');
           }
       });
   });

}


// 修改授课信息
// 点击课程信息
document.querySelectorAll('.course-badge').forEach(badge => {
    badge.addEventListener('click', function() {
        // 移除所有激活状态
        document.querySelectorAll('.course-badge').forEach(b =>
            b.classList.remove('active'));

        // 设置当前选中
        this.classList.add('active');

        // 可以在此处添加课程选择后的其他逻辑
        const courseId = this.dataset.courseId; // 如果徽章有data-course-id属性
        console.log('当前选中课程ID:', courseId);
    });
});
// 在lectures.js中添加以下代码
$(document).ready(function() {
    // 课程点击事件
    $('.course-badge').on('click', function() {
        console.log('点击了课程');
        const courseId = $(this).data('course-id');

        // 发起AJAX请求获取课程详情
        $.ajax({
            url: 'http://localhost:9220/AttendanceSystem/LectureInfoController',
            method: 'GET',
            data: { courseId: courseId },
            success: function(response) {
                console.log('Course details:', response);
                //
                // // 处理授课时间格式
                const lectureTime = new Date(response.lectureTime)
                    .toISOString()
                    .slice(0, 16);
                $('input[name="lectureTime"]').val(lectureTime);
                //
                // // 填充教室信息
                $('input[name="classroom"]').val(response.classroom);
                //
                // // 填充课程标题
                $('input[name="courseTitle"]').val(response.summary);
            },
            error: function() {
                console.error('Failed to load course details');
            }
        });
    });
});

// 添加取消修改功能
document.querySelectorAll('.lecture-btn-cancel').forEach(button => {
    button.addEventListener('click', function() {
        // 获取当前表单容器
        const form = this.closest('.lecture-edit-form');

        // 重置表单到原始状态的三步操作
        // 1. 重置表单字段
        form.reset();

        // 2. 恢复特定字段的初始值
        const originalValues = {
            classroom: '',
            lectureTime: '',
            courseTitle: ''
        };

        // 设置固定字段的值
        form.querySelector('[name="classroom"]').value = originalValues.classroom;
        form.querySelector('[name="lectureTime"]').value = originalValues.lectureTime;
        form.querySelector('[name="courseTitle"]').value = originalValues.courseTitle;

        // 3. 清除验证错误状态
        form.querySelectorAll('.invalid').forEach(element => {
            element.classList.remove('invalid');
        });
        form.querySelectorAll('.error-msg').forEach(msg => {
            msg.style.display = 'none';
        });

        // 扩展功能：关闭编辑面板（可选）
        const editSections = document.querySelectorAll('.course-badge.active'); // 只选择已激活的
        editSections.forEach(section => {
            section.classList.remove('active');
            // 可添加其他操作
            console.log('已移除激活状态:', section);
        });

        // 扩展功能：显示操作反馈（可选）
        showToast('已取消修改，内容已还原', 'success', 1500);
    });
});
//添加确认修改功能
document.querySelector('#edit-lecture .btn-submit').addEventListener('click', function() {
    const form = document.querySelector('.lecture-edit-form');
    console.log('提交按钮被点击');
    console.log('form:', form)

    // 表单验证增强版
    if (!validateEditForm(form)) {
        showToast('请完善所有必填项', 'warning');
        return;
    }

    // 收集表单数据
    const formData = {
        courseId: getSelectedCourseId(),      // 获取当前选中的课程ID
        className: form.querySelector('[name="update_className"]').value,
        lectureTime: form.querySelector('[name="lectureTime"]').value,
        classroom: form.querySelector('[name="classroom"]').value,
        summary: form.querySelector('[name="courseTitle"]').value,
        // 可根据需要添加其他字段
    };
    // console.log('Form data:', formData);

    // 显示加载状态
    const originalBtnText = this.innerHTML;
    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
    this.disabled = true;

    // 发送AJAX请求
    $.ajax({
        url: 'http://localhost:9220/AttendanceSystem/UpdateLectureController',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            showToast('授课信息更新成功', 'success');
            // 可选：更新页面显示
            // updateLectureDisplay(formData);
        },
        error: function(xhr) {
            console.error('更新失败:', xhr.responseText);
            showToast(`更新失败: ${xhr.statusText}`, 'error');
        },
        complete: function() {
            // 恢复按钮状态
            this.disabled = false;
            this.innerHTML = originalBtnText;
        }.bind(this)
    });
});

// 表单验证函数
function validateEditForm(form) {
    let isValid = true;

    // 检查必填字段
    const requiredFields = form.querySelectorAll('[required]');
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            field.classList.add('invalid');
            isValid = false;
        } else {
            field.classList.remove('invalid');
        }
    });

    // 检查课程选择
    if (!getSelectedCourseId()) {
        showToast('请先选择要修改的课程', 'warning');
        isValid = false;
    }

    return isValid;
}

// 获取当前选中的课程ID
function getSelectedCourseId() {
    const activeBadge = document.querySelector('.course-badge.active');
    return activeBadge ? activeBadge.dataset.courseId : null;
}

// 更新页面显示（示例）
function updateLectureDisplay(data) {
    const activeBadge = document.querySelector('.course-badge.active');
    if (activeBadge) {
        // 更新课程信息显示
        activeBadge.querySelector('.course-name').textContent = data.courseTitle;

        // 更新班级显示
        const classOption = document.querySelector(
            `[name="classId"] option[value="${data.classId}"]`
        );
        if (classOption) classOption.selected = true;
    }
}

// 删除授课的勾选功能
document.addEventListener('DOMContentLoaded', function() {
    // 获取全选复选框和所有行复选框
    const checkAll = document.querySelector('.check-all');
    const checkboxes = document.querySelectorAll('.lecture-check');
    const deleteBtn = document.querySelector('.btn-batch-delete');


    // 全选复选框点击事件
    checkAll.addEventListener('change', function() {
        const isChecked = this.checked;
        checkboxes.forEach(checkbox => {
            checkbox.checked = isChecked;
        });
        updateSelectedCount();
        updateDeleteButtonState();
    });

    // 行复选框点击事件
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            // 检查是否所有行都被选中
            const allChecked = [...checkboxes].every(cb => cb.checked);
            checkAll.checked = allChecked;
            updateSelectedCount();
            updateDeleteButtonState();
        });
    });

    // 更新已选择数量


    // 更新删除按钮状态
    function updateDeleteButtonState() {
        deleteBtn.disabled = selectedCount.textContent === '0';
    }
});
//全局方法调用
const selectedCount = document.querySelector('.selected-count .count');
function updateSelectedCount() {
    const checkedCount = document.querySelectorAll('.lecture-check:checked').length;
    selectedCount.textContent = checkedCount;
}


//点击删除按钮
$(document).on('click', '.btn-delete', function() {
    const lectureId = $(this).data('lecture-id');
    const lectureName = $(this).data('lecture-name');
    console.log('lectureId:', lectureId);

    // 确认对话框
    if (!confirm(`确定要删除【${lectureName}】的授课安排吗？`)) return;

    $.ajax({
        timeout: 5000,
        url: 'http://localhost:9220/AttendanceSystem/DeleteLectureController',
        method: 'DELETE',
        contentType: 'application/json', // 必须指定内容类型
        dataType: 'json',
        data: JSON.stringify({ lectureId: lectureId }),
        success: (response) => {
            $(this).closest('tr').fadeOut(300, function() {
                $(this).remove();
                updateSelectedCount(); // 更新计数
            });
            showToast('删除成功', 'success');
            // if (response.success) {
            //     // 移除表格行
            //
            // } else {
            //     showToast(response.message || '删除失败', 'error');
            // }
        },
        error: (xhr) => {
            // 增强错误信息
            const errorMsg = xhr.responseJSON?.error ||
                xhr.responseText ||
                `服务器错误: ${xhr.status} ${xhr.statusText}`;
            console.error('删除失败详情:', {
                status: xhr.status,
                error: errorMsg,
                request: xhr.config
            });
            showToast(`删除失败: ${errorMsg}`, 'error');
        },
    });
});

// 批量删除按钮事件（需补充在现有代码中）
$('.btn-batch-delete').click(function() {
    const ids = [];
    $('.lecture-check:checked').each(function() {
        ids.push($(this).closest('tr').data('lecture-id'));
    });
    console.log(`已选中的授课ID列表：${JSON.stringify(ids)}`);

    $.ajax({
        url: 'http://localhost:9220/AttendanceSystem/BatchDeleteLecturesController',
        method: 'DELETE',
        data: JSON.stringify(ids),
        contentType: 'application/json',
        success: (response) => {
            if (response.success) {
                $('.lecture-check:checked').closest('tr').remove();
                updateSelectedCount();
                showToast(`已删除${ids.length}项`, 'success');
            }
        }
    });
});







